
const { ccclass, property } = cc._decorator;

@ccclass
export default class InputManager extends cc.Component {
    @property(cc.Node)
    touchRoot: cc.Node = null;

    protected onEnable(): void {
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
        this.touchRoot.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    protected onDisable(): void {
        cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
        this.touchRoot.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    onTouchEnd(e: cc.Event.EventTouch) {
        const start = e.getStartLocation();
        const end = e.getLocation();
        const sub = end.sub(start);

        const mag = sub.mag();

        // console.log(`mag: ${mag.toFixed(2)}`);

        if (mag < 50) {
            return true;
        }

        const deltaX = sub.x;
        const deltaY = sub.y;
        const angle = sub.signAngle(cc.v2(1, 0)) * cc.macro.DEG;

        console.log(`deltaX: ${deltaX.toFixed(0)}, deltaY: ${deltaY.toFixed(0)}
mag: ${mag.toFixed(0)}, angle: ${angle.toFixed(0)}`);

        let event = '';

        if (angle < 45 && angle > -45) {
            event = 'go-right';
        } else if (angle > 45 && angle < 135) {
            event = 'go-down';
        } else if (angle > 135 || angle < -135) {
            event = 'go-left';
        } else {
            event = 'go-up';
        }

        this.node.emit(event);
    }

    protected onKeyDown(e: cc.Event.EventKeyboard) {
        const code = e.keyCode;

        let event = '';
        switch (code) {
            case cc.macro.KEY.up:
                event = 'go-up';
                break;
            case cc.macro.KEY.down:
                event = 'go-down';
                break;
            case cc.macro.KEY.left:
                event = 'go-left';
                break;
            case cc.macro.KEY.right:
                event = 'go-right';
                break;
            default:
                console.log(`Wrong Key: ${code}, Use Up Down Left Right`);
                return;
        }

        if (!event) return;

        // console.log(event);
        this.node.emit(event);
    }
}
